package com.qire.manhua.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.annotation.Nullable;

@SuppressLint("AppCompatCustomView")
public class BottomAlignImageView extends ImageView {

    public BottomAlignImageView(Context context) {
        super(context);
    }

    public BottomAlignImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public BottomAlignImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onDraw(Canvas canvas) {
//        super.onDraw(canvas);

        Drawable drawable = getDrawable();
        if (drawable == null) {
            return; // couldn't resolve the URI
        }

        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        if (width == 0 || height == 0) {
            return;     // nothing to draw (empty bounds)
        }

        //支持底部对齐绘制代码 start
        int viewHeight = getMeasuredHeight();
        int moveY      = viewHeight - height;
        canvas.translate(0,moveY/2);
        //支持底部对齐绘制代码 end

        Matrix drawMatrix   = getImageMatrix();
        int    paddingTop   = getPaddingTop();
        int    paddingLeft  = getPaddingLeft();

        if (drawMatrix == null && paddingTop == 0 && paddingLeft == 0) {
            drawable.draw(canvas);
        } else {
            final int saveCount = canvas.getSaveCount();
            canvas.save();

            boolean cropToPadding = getCropToPadding();
            if (cropToPadding) {
                final int scrollX = getScrollX();
                final int scrollY = getScrollY();

                int paddingRight  = getPaddingLeft();
                int paddingBottom = getPaddingLeft();

                int right   = getRight();
                int left    = getLeft();
                int top     = getTop();
                int bottom  = getBottom();

                canvas.clipRect(scrollX + paddingLeft, scrollY + paddingTop,
                        scrollX + right - left - paddingRight,
                        scrollY + bottom - top - paddingBottom);
            }

            canvas.translate(paddingLeft, paddingTop);

            if (drawMatrix != null) {
                canvas.concat(drawMatrix);
            }
            drawable.draw(canvas);
            canvas.restoreToCount(saveCount);
        }

        //支持底部对齐绘制代码 start
        canvas.translate(0,-moveY);
        //支持底部对齐绘制代码 end

    }
}
